package com.jiyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiyun.entity.*;
import com.jiyun.mapper.TaskMapper;
import com.jiyun.mapper.TaskTypeMapper;
import com.jiyun.mapper.UserMapper;
import com.jiyun.mapper.UserTaskMapper;
import com.jiyun.service.ITaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 聪哥哥
 * @since 2023-03-10
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    @Autowired
    TaskMapper taskMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    TaskTypeMapper taskTypeMapper;

    @Autowired
    UserTaskMapper userTaskMapper;

    @Override
    public Page<TaskDTO> taskPage(Page<Task> taskPage, Map<String,String> map) {
        // date 0 所有时间段   1 今天  2 昨天  3 一周内
        String date = map.get("date");
        LambdaQueryWrapper<Task> qw = new LambdaQueryWrapper<>();

        String name = map.get("name");
        qw.like(StringUtils.isNotBlank(name),Task::getTitle,name);

        String status = map.get("status");
        if(!status.equals("5")){
            qw.eq(Task::getStatus,status);
        }

        Integer typeId = Integer.parseInt(map.get("type"));
        if(typeId!=0){
            qw.eq(Task::getTid,typeId);
        }


        if(date.equals("1")){
            LocalDateTime start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
            // greater or equel then &gt  &lt
            qw.ge(Task::getStartTime,start);
            qw.le(Task::getStartTime,end);

        }else if(date.equals("2")){
            // 得到当前日期的，-1天之后
            LocalDateTime start = LocalDateTime.of(LocalDate.now().plusDays(-1), LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(LocalDate.now().plusDays(-1), LocalTime.MAX);
            // greater or equel then &gt  &lt
            qw.ge(Task::getStartTime,start);
            qw.le(Task::getStartTime,end);

        }else if(date.equals("3")){
            LocalDateTime start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            LocalDateTime end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

            qw.ge(Task::getStartTime,start);
            qw.le(Task::getStartTime,end);
        }


        taskMapper.selectPage(taskPage,qw);

        // 找关联的对象
        List<Task> records = taskPage.getRecords();
        List<TaskDTO> list = new ArrayList<>();
        for (Task record : records) {
            // 任务类型的id
            Integer tid = record.getTid();
            TaskType taskType = taskTypeMapper.selectById(tid);
            // 负责人的id
            Integer directorId = record.getDirectorId();
            User director = userMapper.selectById(directorId);
            // 监督者的id
            Integer supervisorId = record.getSupervisorId();
            User supervisor = userMapper.selectById(supervisorId);
            TaskDTO taskDTO = new TaskDTO();
            BeanUtils.copyProperties(record,taskDTO);
            taskDTO.setDirector(director);
            taskDTO.setSupervisor(supervisor);
            taskDTO.setTaskType(taskType);
            list.add(taskDTO);
        }

        // 将Page<Task>对象，复制给Page<TaskDTO>对象
        Page<TaskDTO> dtoPage = new Page<>();
        // 将taskPage对象中的值，复制给dtoPage
        BeanUtils.copyProperties(taskPage,dtoPage);

        dtoPage.setRecords(list);

        return dtoPage;
    }

    @Override
    public List<Integer> findZhong(Integer tid) {
        return userTaskMapper.findZhong(tid);
    }

    @Override
    public void insert(Task task, List<Integer> ids) {
        task.setPid(0);
        taskMapper.insert(task);
        // 任务的id ， 任务参与者的id
        for (Integer id : ids) {
            UserTask userTask = new UserTask();
            userTask.setTid(task.getId());
            userTask.setUid(id);
            userTaskMapper.insert(userTask);
        }

    }

    @Override
    public void updateTask(Task task, List<Integer> ids) {
        taskMapper.updateById(task);
        // 中间表。先断开所有的关系，然后再把关系加回来
        userTaskMapper.deleteZhong(task.getId());
        for (Integer id : ids) {
            UserTask userTask = new UserTask();
            userTask.setTid(task.getId());
            userTask.setUid(id);
            userTaskMapper.insert(userTask);
        }
    }

    @Override
    public List<TaskDTO> findAll() {
        // 查询所有任务
        List<Task> tasks = taskMapper.selectList(null);
        List<TaskDTO> list = new ArrayList<>();
        for (Task task : tasks) {

            Integer directorId = task.getDirectorId();
            User director = userMapper.selectById(directorId);
            // 复制数据，从task到dto
            TaskDTO taskDTO = new TaskDTO();
            BeanUtils.copyProperties(task,taskDTO);
            taskDTO.setDirector(director);
            list.add(taskDTO);
        }
        return list;
    }

    @Override
    public List<Task> findAllOutId(Integer id) {
        LambdaQueryWrapper<Task> qw = new LambdaQueryWrapper<>();
        // not equrls  不相等
        qw.ne(Task::getId,id);
        return taskMapper.selectList(qw);
    }

    @Override
    public List<Integer> findTaskChildren(Integer pid) {
        return taskMapper.findTaskChildren(pid);
    }

    @Override
    public void addChildrenTask(Integer pid, List<Integer> ids) {
        // 由于关联的数据会有很多，如果我们把期中一条调整没了
        // 有一条应该没有了
        taskMapper.updateByPid(pid);

        // 正常的修改的数据
        for (Integer id : ids) {
            // 需要被修改的那些任务的id
            Task task = new Task();
            task.setId(id);
            task.setPid(pid);
            taskMapper.updateById(task);
        }
    }

    @Override
    public Page<TaskDTO> task2Page(Page<Task> taskPage) {

        LambdaQueryWrapper<Task> qw = new LambdaQueryWrapper<>();
        qw.eq(Task::getStatus,"2");

        taskMapper.selectPage(taskPage,qw);

        // 找关联的对象
        List<Task> records = taskPage.getRecords();
        List<TaskDTO> list = new ArrayList<>();
        for (Task record : records) {
            // 任务类型的id
            Integer tid = record.getTid();
            TaskType taskType = taskTypeMapper.selectById(tid);
            // 负责人的id
            Integer directorId = record.getDirectorId();
            User director = userMapper.selectById(directorId);
            // 监督者的id
            Integer supervisorId = record.getSupervisorId();
            User supervisor = userMapper.selectById(supervisorId);
            TaskDTO taskDTO = new TaskDTO();
            BeanUtils.copyProperties(record,taskDTO);
            taskDTO.setDirector(director);
            taskDTO.setSupervisor(supervisor);
            taskDTO.setTaskType(taskType);
            list.add(taskDTO);
        }

        // 将Page<Task>对象，复制给Page<TaskDTO>对象
        Page<TaskDTO> dtoPage = new Page<>();
        // 将taskPage对象中的值，复制给dtoPage
        BeanUtils.copyProperties(taskPage,dtoPage);

        dtoPage.setRecords(list);

        return dtoPage;
    }

    @Override
    public void verify(Integer id, String status) {
        Task task = new Task();
        task.setId(id);
        task.setStatus(status);
        taskMapper.updateById(task);
    }
}
